﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.DomainServices.Server;
using System.Web.Security;

namespace OpenLightGroup.Common.UserManagement.Web
{
    public partial class UserManagementService : DomainService
    {

        /// <summary>
        /// Role to which users will be added by default.
        /// </summary>
        public const string DefaultRole = "Registered Users";

        //// NOTE: This is a sample code to get your application started. In the production code you would 
        //// want to provide a mitigation against a denial of service attack by providing CAPTCHA 
        //// control functionality or verifying user's email address.

        /// <summary>
        /// Adds a new user with the supplied <see cref="UserRegistration"/> and <paramref name="password"/>.
        /// </summary>
        /// <param name="user">The registration information for this user.</param>
        /// <param name="password">The password for the new user.</param>
        [Invoke(HasSideEffects = true)]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
        public CreateUserStatus CreateUser(UserRegistration user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            // Run this BEFORE creating the user to make sure roles are enabled and the default role
            // will be available
            //
            // If there are a problem with the role manager it is better to fail now than to have it
            // happening after the user is created
            if (!Roles.RoleExists(UserManagementService.DefaultRole))
            {
                Roles.CreateRole(UserManagementService.DefaultRole);
            }

            // NOTE: ASP.NET by default uses SQL Server Express to create the user database. 
            // CreateUser will fail if you do not have SQL Server Express installed.
            MembershipCreateStatus createStatus;
            Membership.CreateUser(user.UserName, user.Password, user.Email, user.Question, user.Answer, true, null, out createStatus);

            if (createStatus != MembershipCreateStatus.Success)
            {
                return UserManagementService.ConvertStatus(createStatus);
            }


            if (!user.Roles.Contains(UserManagementService.DefaultRole))
            {
                // Assign it to the default role
                // This *can* fail but only if role management is disabled
                Roles.AddUserToRole(user.UserName, UserManagementService.DefaultRole);

            }

            Roles.AddUserToRoles(user.UserName, user.Roles.ToArray());



            // Set its friendly name (profile setting)
            // This *can* fail but only if Web.config is configured incorrectly 
            //ProfileBase profile = ProfileBase.Create(user.UserName, true);
            //profile.SetPropertyValue("FriendlyName", user.FriendlyName);
            //profile.Save();

            return CreateUserStatus.Success;
        }

        private static CreateUserStatus ConvertStatus(MembershipCreateStatus createStatus)
        {
            switch (createStatus)
            {
                case MembershipCreateStatus.Success:
                    return CreateUserStatus.Success;
                case MembershipCreateStatus.InvalidUserName:
                    return CreateUserStatus.InvalidUserName;
                case MembershipCreateStatus.InvalidPassword:
                    return CreateUserStatus.InvalidPassword;
                case MembershipCreateStatus.InvalidQuestion:
                    return CreateUserStatus.InvalidQuestion;
                case MembershipCreateStatus.InvalidAnswer:
                    return CreateUserStatus.InvalidAnswer;
                case MembershipCreateStatus.InvalidEmail:
                    return CreateUserStatus.InvalidEmail;
                case MembershipCreateStatus.DuplicateUserName:
                    return CreateUserStatus.DuplicateUserName;
                case MembershipCreateStatus.DuplicateEmail:
                    return CreateUserStatus.DuplicateEmail;
                default:
                    return CreateUserStatus.Failure;
            }
        }

        public IEnumerable<UserRegistration> GetUserRegistrations()
        {
            return new List<UserRegistration>();
        }
    }
}
